/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.ui.cd.point;

import java.awt.Color;
import java.util.Collections;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

import org.apache.log4j.Logger;

import who.tmap.bo.cd.CDPointSymbols;
import who.tmap.bo.cd.CDTypes;
import who.tmap.bo.cd.point.CDPointDataDrivenEntry;
import who.tmap.services.ColorService;
import who.tmap.services.TextureService;
import who.tmap.ui.util.jsorttable.ColumnComparator;
import who.tmap.ui.util.jsorttable.SortTableModel;

/**
 * @author stl
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class CDPointTableModel extends AbstractTableModel
						       implements SortTableModel {
		
    private static Logger logger = Logger.getLogger(CDPointTableModel.class); 
	private static final TextureService textureHelper =TextureService.getInstance();
	
	private static final int VALUE_COL =0;
	public static final int SYMBOL_COL =1;	
	public static final int COLOR_COL =2;
	public static final int FILL_PATTERN_COL =3;
	public static final int SIZE_COL =4;
	
	private String[] columnNames = null;
	private String[] columnNamesSymbol = { "Value", "Symbol", "Color", "Pattern", "Size" };	
	private String[] columnNamesSymbolAndSize = { "Value", "Symbol", "Color", "Pattern" };		
	
	private List<CDPointDataDrivenEntry> rows;	
	private ColorService[] colorServices;
	private boolean dirty =false;	
	
	public CDPointTableModel( int mappingType ) {
		super();
		
		if ( mappingType == CDTypes.POINT_DATA_DRIVEN_SYMBOL ) {
			columnNames =columnNamesSymbol;
		} else {
			columnNames =columnNamesSymbolAndSize;
		}
	}
	
	public boolean isDirty() {
		return dirty;
	}

	public void setDirty(boolean dirty) {
		this.dirty = dirty;
	}
	
	public void setRows( List<CDPointDataDrivenEntry> rows ) {
		this.rows =rows;
		
		setDirty( false );
		
        fireTableDataChanged();
	}	
	
	public void setColorServices(ColorService[] colorServices) {
		this.colorServices = colorServices;
	}

	public List<CDPointDataDrivenEntry> getRows() {
		return rows;
	}
										  
	public int getColumnCount() {
		return columnNames.length;
	}

	public int getRowCount() {
		return rows !=null ? rows.size() : 0;
	}

	public String getColumnName(int col) {
		return columnNames[col];
	}

	public Object getValueAt(int row, int col) {
		Object obj =null;
		
		CDPointDataDrivenEntry entry =(CDPointDataDrivenEntry)rows.get( new Integer( row ) );
		
		switch( col ) {
			case VALUE_COL:
				obj =entry.getVal();
				break;
				
			case SYMBOL_COL:
				obj =CDPointSymbols.names[ entry.getSymbol() ];
				break;
				
			case COLOR_COL:
				obj =new Integer( colorServices[ row ].getIndexForColor( entry.getColor() ) );
				break;
			
			case FILL_PATTERN_COL:
				obj =new Integer( entry.getFillPattern() );			
				break;
				
			case SIZE_COL:
				obj =new Integer( entry.getSize() );
				break;
		}
		
		return obj;
	}
	
    public void setValueAt(Object value, int row, int col) {

		CDPointDataDrivenEntry entry =(CDPointDataDrivenEntry)rows.get( new Integer( row ) );
		
		switch( col ) {
			case VALUE_COL:
				entry.setVal( (String)value );
				break;
				
			case SYMBOL_COL:
				String symbolName =(String)value;
				int symbolIdx =getIndexForCDPointSymbolName( symbolName );
				entry.setSymbol( symbolIdx );
				break;
				
			case COLOR_COL:
				int idx =((Integer)value).intValue();
				Color color =colorServices[ row ].getColors()[ idx ];
				entry.setColor( color );
				break;

			case FILL_PATTERN_COL:
				entry.setFillPattern( ((Integer)value).intValue() );
				break;
				
			case SIZE_COL:
				entry.setSize( ((Integer)value).intValue() );
				break;
			
		}
    	                    
        fireTableCellUpdated(row, col);
        
        setDirty( true );
    }	

	/*
	 * JTable uses this method to determine the default renderer/
	 * editor for each cell.  If we didn't implement this method,
	 * then the last column would contain text ("true"/"false"),
	 * rather than a check box.
	 */
	@SuppressWarnings("unchecked")
	public Class getColumnClass(int c) {
		return getValueAt(0, c).getClass();
	}

	/*
	 * Don't need to implement this method unless your table's
	 * editable.
	 */
	public boolean isCellEditable(int row, int col) {
		return col != VALUE_COL;
	}

    /* (non-Javadoc)
     * @see who.tmap.ui.util.SortTableModel#isSortable(int)
     */
    public boolean isSortable(int col) {
        return true;
    }

    /* (non-Javadoc)
     * @see who.tmap.ui.util.SortTableModel#sortColumn(int, boolean)
     */
    @SuppressWarnings("unchecked")
	public void sortColumn(int col, boolean ascending) {
        try {
            Collections.sort( rows, new ColumnComparator(col, ascending) );
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(null,
    	            "This column contains an invalid entry which prevents it to be correctly sorted.",
    	            "TMap error",
    	            JOptionPane.ERROR_MESSAGE);   
        }
        
    } 
    
    private int getIndexForCDPointSymbolName( String name ) {
    	int idx =-1;
    	
    	for( int ct =0; ct < CDPointSymbols.names.length; ct++ ) {
    		if ( CDPointSymbols.names[ ct ].equals( name ) ) {
    			idx =ct;
    			break;
    		}
    	}
    	
    	return idx;
    }
     
}
